package cn.kgc.springcloud.controller;

import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.entity.ClazzVO;
import cn.kgc.springcloud.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/4/28
 * @Description:
 */
@RestController
@RequestMapping("clazz")
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    @DeleteMapping("{id}")
    public Boolean delete(@PathVariable("id") Integer id) {
        boolean b = clazzService.removeById(id);
        return b;
    }

    @GetMapping
    public List<ClazzVO> getList() {
        return    clazzService.getList();
    }

    @PostMapping
    public Clazz add(MultipartFile file,String name,Integer tagId){

        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid+"."+filenameExtension;

        try {
            file.transferTo(new File("D:/upload/"+fileName));
            Clazz clazz = new Clazz();
            clazz.setName(name);
            clazz.setTagid(tagId);
            clazz.setPath(fileName);
            clazzService.save(clazz);
            return clazz;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @GetMapping("{id}")
    public Clazz getById(@PathVariable("id") Integer id){
        return   clazzService.getById(id);
    }


}
